from 数据库操作.CreateMysqlCon import CreateMysqlCon

class CommentOperation:
    def __init__(self):
        self.con = CreateMysqlCon().get_con()
        if not self.con:
            raise ConnectionError("数据库连接失败，请检查配置或网络")
        self.cursor = self.con.cursor()

    def add_comment(self, blog_id, user_id, content):
        """添加评论"""
        try:
            sql = "INSERT INTO comments (blog_id, user_id, content) VALUES (%s, %s, %s)"
            self.cursor.execute(sql, (blog_id, user_id, content))
            self.con.commit()
            return True
        except Exception as e:
            print(f"添加评论失败: {e}")
            return False

    def get_comments_by_blog(self, blog_id):
        """获取博客的所有评论"""
        try:
            sql = """SELECT c.ID, u.username, c.content, c.comment_time 
                   FROM comments c 
                   JOIN user_data u ON c.user_id = u.ID 
                   WHERE c.blog_id = %s 
                   ORDER BY c.comment_time DESC"""
            self.cursor.execute(sql, (blog_id,))
            return self.cursor.fetchall()
        except Exception as e:
            print(f"获取评论失败: {e}")
            return []

    def delete_comment(self, comment_id, user_id):
        """删除评论（只能删除自己的评论）"""
        try:
            # 先检查是否是自己的评论
            self.cursor.execute("SELECT user_id FROM comments WHERE ID = %s", (comment_id,))
            result = self.cursor.fetchone()
            if not result or result[0] != user_id:
                return False  # 不是自己的评论或评论不存在
            
            sql = "DELETE FROM comments WHERE ID = %s"
            self.cursor.execute(sql, (comment_id,))
            self.con.commit()
            return True
        except Exception as e:
            print(f"删除评论失败: {e}")
            return False